<template>
  <el-container>
    <el-header >
      <h2>问题管理</h2>
      <el-button @click="addproblem" size="default" type="warning" style="position: absolute;left: 270px;top: 50px">
        新增问题
      </el-button>
    </el-header>

    <el-main>
      <el-table :data="problemList" style="width: 100%" stripe>
        <el-table-column label="问题ID" prop="problemId" width="100" />
        <el-table-column label="问题内容" prop="description" width="300" />
        <el-table-column label="分数" prop="point" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button @click="editProblem(row)" size="small" type="primary">编辑</el-button>
            <el-button @click="deleteProblem(row.problemId)" size="small" type="danger" style="margin-left: 10px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
      />
    </el-main>
  </el-container>
</template>

<script>
import { ref, onMounted } from 'vue';
import { fetchProblemList, deleteProblem } from '@/api/problem';
import router from "@/router/index.js";

export default {
  setup() {
    const problemList = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const handlePageChange = (page) => {
      currentPage.value = page;
      loadProblemList();
    };
    // 加载问题列表
    function addproblem() {
      router.push("/problem")
    }
    const loadProblemList = async () => {
      const { data } = await fetchProblemList();
      console.log(data);
      problemList.value = data;
      total.value = data.total;
    };

    // 删除问题
    const deleteProblemHandler = async (id) => {
      try {
        await deleteProblem(id);
        await loadProblemList(); // 刷新列表
      } catch (error) {
        console.error('删除失败', error);
      }
    };

    // 分页处理


    onMounted(() => {
      loadProblemList();
    });

    return {
      problemList,
      currentPage,
      pageSize,
      total,
      addproblem,
      loadProblemList,
      deleteProblem: deleteProblemHandler,
      editProblem: (row) => {
        router.push(`/problem/${row.problemId}`);
        console.log('编辑问题:', row); // 编辑操作
      },
    };
  },
};
</script>

<style scoped>
.el-header {
  background-color: #409eff;
  color: white;
  padding: 10px;
  text-align: center;
}

h2 {
  margin: 0;
}

.el-main {
  padding: 20px;
}
</style>
